# -*- coding: utf-8 -*-
# ===========================================
# @Time    : 2021/9/14 9:29 
# @Author  : shutao
# @FileName: general_utils.py
# @remark  : 
# 
# @Software: PyCharm
# Github 　： https://github.com/NameLacker
# ===========================================

import random
import paddle
import time
import os

from loguru import logger


def PRAYER():
    """
    佛祖保佑，永无BUG
    如遇开光失败，请重启此项目
    Returns:
        开光后的代码
    """
    if random.random() >= 0.5:
        code_file = "../docs/code1.txt" if os.access("../docs/code1.txt", os.F_OK) else "docs/code1.txt"
        spk = "       佛祖镇楼                  BUG退避"
        project_amulet = True
    else:
        code_file = "../docs/code2.txt" if os.access("../docs/code2.txt", os.F_OK) else "docs/code2.txt"
        spk = "             佛曰：bug泛滥，我已瘫痪！"
        project_amulet = False

    with open(code_file, 'r') as f:
        amtf = f.readlines()
    for code in amtf:
        logger.warning(code.replace("\n", "").replace("\t", ""))
    logger.warning(spk)
    logger.warning("============= 此项目代码受佛祖庇佑 ==============") \
        if project_amulet \
        else logger.warning("========= 此项目代码把佛祖整瘫痪了，请重启 =========")

    time.sleep(3)
    return project_amulet


def ele_sub(T: paddle.Tensor, a, b):
    """
    Element replacement
    Args:
        T: Paddle tensor
        a: Original value
        b: The value to replace

    Returns:
        T: Paddle tensor after replace.
    """
    t = paddle.ones_like(T) * a
    t = T.equal(t).astype(paddle.int64) * b
    T = paddle.where(T == a, t, T)
    return T


def save(obj, path):
    """
    保存模型参数
    Args:
        obj:
        path:

    Returns:

    """
    paddle.save(obj, path)


def load(file_name):
    """
    加载模型参数
    Args:
        file_name:

    Returns:

    """
    if not os.path.isfile(file_name):
        raise IOError("{} not exist".format(file_name))
    return paddle.load(file_name)
